package com.example.administrator.hqq.activity;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.administrator.hqq.MainActivity;
import com.example.administrator.hqq.R;
import com.example.administrator.hqq.base.MyActivity;
import com.example.administrator.hqq.base.MyApplication;
import com.example.administrator.hqq.bean.RegisterBeen;
import com.example.administrator.hqq.bean.VerifcationBean;
import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.config.UrlFactory;
import com.example.administrator.hqq.utils.HintWordsUtils;
import com.example.administrator.hqq.utils.VerificationUtils;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.GetBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @author 康海涛
 * @describe: 登录注册页面
 */
public class LogInActivity extends MyActivity {

    @BindView(R.id.user_number)
    EditText userNumber;
    @BindView(R.id.verification)
    Button verification;
    @BindView(R.id.verification_code1)
    EditText verificationCode1;
    @BindView(R.id.verification_code2)
    EditText verificationCode2;
    @BindView(R.id.verification_code3)
    EditText verificationCode3;
    @BindView(R.id.verification_code4)
    EditText verificationCode4;
    @BindView(R.id.verification_code5)
    EditText verificationCode5;
    @BindView(R.id.verification_code6)
    EditText verificationCode6;
    @BindView(R.id.begin)
    Button begin;
    @BindView(R.id.succeed_text)
    TextView succeedText;
    @BindView(R.id.user_agreement)
    TextView userAgreement;
    @BindView(R.id.user_privacy)
    TextView userPrivacy;
    private TimeCount time;
    private List<EditText> editTexts;
    private String TAG = this.getClass().getSimpleName();
    private String code = "";
    private boolean aBoolean = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_log_in);
        ButterKnife.bind(this);
        SPUtils.getInstance().put(LoongsConfig.guide,true);
        initview();
        initData();

    }

    /**
     * @param i 用于处理输入框后退键
     */
    private void backFocus(int i) {
        long startTime = System.currentTimeMillis();
        if (i == 0) {
            editTexts.get(i).setText("");

        } else {
            editTexts.get(i - 1).requestFocus();
            editTexts.get(i).setText("");
        }
        aBoolean = true;
    }

    @OnClick({R.id.verification, R.id.begin,R.id.user_agreement,R.id.user_privacy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.verification:
                if (VerificationUtils.isMobileNO(userNumber.getText().toString())) {
                    getVerificationCode();
                } else {
                    Toast.makeText(this, "输入的手机号有误", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.begin:
                login();
                break;
            case R.id.user_agreement:
                UserAgreementActivity.startActivity(this,LoongsConfig.agreement,"用户协议");
                break;
            case R.id.user_privacy:
                UserAgreementActivity.startActivity(this,LoongsConfig.privacy,"隐私协议");
                break;
        }
    }

    /**
     * 登录接口
     */
    private void login() {
        if (VerificationUtils.isMobileNO(userNumber.getText().toString())) {
            code = "";
            for (int i = 0; i < editTexts.size(); i++) {
                code = code + editTexts.get(i).getText();
            }
            if (code.length() == 6) {
                if (isSoftShowing()) {
                    final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                }
                showLoadingDialog();
                GetBuilder tag = OkHttpUtils.get().url(UrlFactory.UserLogin()).tag(this);
                tag.addParams(LoongsConfig.phone, userNumber.getText().toString())
                        .addParams(LoongsConfig.code, code)
                        .build().execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e(TAG, "onError:" + e.getMessage());
                        ToastUtils.showShort("登录失败请稍重试");
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onResponse(String s, int id) {
                        dismissLoadingDialog();
                        Log.e(TAG, "onResponse: " + s);
                        Gson gson = new Gson();
                        RegisterBeen registerBeen = gson.fromJson(s, RegisterBeen.class);
                        HintWordsUtils.showMarkeWords(registerBeen.getCode(),registerBeen.getDescription());
                        if (registerBeen.getCode() == 202) {
                            SPUtils.getInstance().put(LoongsConfig.user_phone,userNumber.getText().toString());
                            SPUtils.getInstance().put(LoongsConfig.user_id, registerBeen.getUser_id());
                            //为融云设置别名
                            MyApplication.setUMAlias(registerBeen.getUser_id());
                            Intent intent = new Intent(LogInActivity.this, SetInformationActivity.class);
                            intent.putExtra(LoongsConfig.phone, userNumber.getText().toString());
                            intent.putExtra(LoongsConfig.code, code);
                            startActivity(intent);
                            finish();
                        } else if (registerBeen.getCode() == 201) {
                            SPUtils.getInstance().put(LoongsConfig.user_phone,userNumber.getText().toString());
                            String login_token = registerBeen.getLogin_token();
                            String rongyun_token = registerBeen.getRongyun_token();
                            String user_id = registerBeen.getUser_id();
                            String gender = registerBeen.getGender();
                            SPUtils.getInstance().put(LoongsConfig.gender, gender);
                            //为融云设置别名
                            MyApplication.setUMAlias(user_id);
                            Log.e(TAG, "rongyun_token: " + rongyun_token);
                            SPUtils.getInstance().put(LoongsConfig.user_id, user_id);
                            SPUtils.getInstance().put(LoongsConfig.loginToken, login_token);
                            SPUtils.getInstance().put(LoongsConfig.rongToken, rongyun_token);
                            Intent intent = new Intent(LogInActivity.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                        }
                    }
                });
            } else {
                Toast.makeText(this, "验证码输入有误", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "输入的手机号有误", Toast.LENGTH_SHORT).show();
        }
    }

    private void initData() {
        time = new TimeCount(60000, 1000);
    }

    private void initview() {
        editTexts = new ArrayList<>();
        editTexts.add(verificationCode1);
        editTexts.add(verificationCode2);
        editTexts.add(verificationCode3);
        editTexts.add(verificationCode4);
        editTexts.add(verificationCode5);
        editTexts.add(verificationCode6);
        //设置输入框返回接听
        String userPhone = SPUtils.getInstance().getString(LoongsConfig.user_phone);
        if (!TextUtils.isEmpty(userPhone))
        {
            userNumber.setText(userPhone);
        }
        for (int i = 0; i < editTexts.size(); i++) {
            editTexts.get(i).setInputType(EditorInfo.TYPE_CLASS_PHONE);
            //设置输入框内容变更监听
            final int finalI = i;
            editTexts.get(i).addTextChangedListener(new TextWatcher() {

                private CharSequence temp;
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    temp = charSequence;
                }

                @Override
                public void afterTextChanged(Editable editable) {
                    int selectionStart = editTexts.get(finalI).getSelectionStart();
                    int selectionEnd = editTexts.get(finalI).getSelectionEnd();
                    Log.e(TAG, "selectionStart:     " + selectionStart + "     selectionEnd:     " + selectionEnd
                            + "   editable:  " + editable + "   temp " + temp.length());
                    //当输入框内容为空时将光标向前移动
                    if (selectionEnd == 0) {
                        if (finalI != 0 && temp.length() == 0) {
                            editTexts.get(finalI - 1).requestFocus();
                            editTexts.get(finalI - 1).setSelection(editTexts.get(finalI - 1).getText().toString().length());
                        } else {
                            editTexts.get(finalI).setSelection(editTexts.get(finalI).getText().toString().length());
                        }
                    }
                    //当输入框内容改变长度为1时候就自动向前移动
                    else if (selectionEnd == 1) {
                        if (finalI != 5 && editTexts.get(finalI).getText().length() == 1) {
                            editTexts.get(finalI + 1).requestFocus();
                            editTexts.get(finalI + 1).setSelection(editTexts.get(finalI + 1).getText().toString().length());
                        } else {
                            char[] chars = editTexts.get(finalI).getText().toString().toCharArray();
                            editTexts.get(finalI).setText("" + chars[selectionEnd - 1]);
                            if (finalI != 5 && editTexts.get(finalI).getText().length() == 1) {
                                editTexts.get(finalI + 1).requestFocus();
                                editTexts.get(finalI + 1).setSelection(editTexts.get(finalI + 1).getText().toString().length());
                            } else {
                                if (!TextUtils.isEmpty(editTexts.get(5).getText()))
                                    login();
                            }
                        }
                    }
                    //当内容改变为大于6时候输入框
                    else if (selectionEnd == 6) {
                        char[] chars = editTexts.get(finalI).getText().toString().toCharArray();
                        for (int i1 = 0; i1 < chars.length; i1++) {
                            if (i1 >= 6) {
                                break;
                            }
                            editTexts.get(i1).setText("" + chars[i1]);
                            editTexts.get(i1).requestFocus();
                            editTexts.get(i1).setSelection(editTexts.get(i1).getText().toString().length());
                            if (i1 == 5) {
                                if (!TextUtils.isEmpty(editTexts.get(5).getText()))
                                    login();
                            }
                        }
                    } else {
                        if (editTexts.get(finalI).getText().toString().length() > 1) {
                            char[] chars = editTexts.get(finalI).getText().toString().toCharArray();
                            editTexts.get(finalI).setText("" + chars[selectionEnd - 1]);
                            if (finalI == 5) {
                                if (!TextUtils.isEmpty(editTexts.get(5).getText()))
                                    login();
                            }
                            if (finalI != 5 && editTexts.get(finalI).getText().length() == 1)
                                editTexts.get(finalI + 1).requestFocus();
                        }

                    }
                }
            });
        }
    }

    private long time1 = -1;
    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - time1 > 2000) {
            ToastUtils.showShort("再次点击退出应用");
            time1 = System.currentTimeMillis();
        } else {
                AppUtils.exitApp();
        }
    }
    //获取短信验证码接口
    public void getVerificationCode() {
        time.start();
        succeedText.setText("已发送6位验证码至手机号+86 " + userNumber.getText().toString());
        succeedText.setVisibility(View.VISIBLE);
        OkHttpUtils.get().url(UrlFactory.getUserVerificationCode()).tag(this)
                .addParams(LoongsConfig.phone, userNumber.getText().toString())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {


                Log.e(TAG, e.getMessage());
                Toast.makeText(LogInActivity.this, "验证码发送失败请稍后重试", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String s, int id) {
                Gson gson = new Gson();
                VerifcationBean verifcationBean = gson.fromJson(s, VerifcationBean.class);
                if (verifcationBean.getCode() == 200) {

                }
            }
        });
    }

    /**
     * 短信即时器
     */
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            //参数依次为总时长,和计时的时间间隔
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {//计时完毕时触发
            if (null != verification) {
                verification.setText("重新发送");
                verification.setClickable(true);
                verification.setSelected(false);
            }
        }

        @Override
        public void onTick(long millisUntilFinished) {//计时过程显示
            if (null != verification) {
                verification.setClickable(false);
                verification.setSelected(true);
                verification.setText(millisUntilFinished / 1000 + "秒");
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected String getActivityName() {
        return this.getClass().getSimpleName();
    }

    /**
     * 判断输入框是否显示
     *
     * @return
     */
    private boolean isSoftShowing() {
        //获取当前屏幕内容的高度
        int screenHeight = getWindow().getDecorView().getHeight();
        //获取View可见区域的bottom
        Rect rect = new Rect();
        getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        return screenHeight - rect.bottom - getSoftButtonsBarHeight() != 0;
    }

    /**
     * 底部虚拟按键栏的高度
     *
     * @return
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    private int getSoftButtonsBarHeight() {
        DisplayMetrics metrics = new DisplayMetrics();
        //这个方法获取可能不是真实屏幕的高度
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int usableHeight = metrics.heightPixels;
        //获取当前屏幕的真实高度
        getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
        int realHeight = metrics.heightPixels;
        if (realHeight > usableHeight) {
            return realHeight - usableHeight;
        } else {
            return 0;
        }
    }
}
